<?php

/**
 * This file is part of Webman AI.
 *
 * @author    walkor<walkor@workerman.net>
 * @copyright walkor<walkor@workerman.net>
 * @link      http://www.workerman.net/
 */

namespace plugin\ai\app\handler\driver;

use Throwable;

class Base
{

    /**
     * @var string api
     */
    protected $api = '';

    /**
     * @var mixed|string apikey
     */
    protected $apikey = '';

    /**
     * @var mixed|string[] default headers
     */
    protected $defaultHeaders = [
        'Content-Type' => 'application/json'
    ];

    /**
     * @param array $options
     */
    public function __construct(array $options = [])
    {
        $this->api = rtrim($options['api'] ?? $this->api, '/');
        $this->apikey = $options['apikey'] ?? '';
        $this->defaultHeaders = array_merge($this->defaultHeaders, $options['headers'] ?? []);
    }

    /**
     * Get headers.
     * @param $options
     * @return string[]
     */
    protected function getHeaders($options): array
    {
        $defaultHeaders = array_merge($this->defaultHeaders, $options['headers'] ?? []);
        return array_merge($defaultHeaders, $options['headers'] ?? []);
    }

    /**
     * Format options.
     * @param array $options
     * @return array
     */
    public function formatOptions(array $options)
    {
        foreach (['complete', 'stream'] as $key) {
            $options[$key] = function (...$args) use ($options, $key) {
                try {
                    if ($options[$key]) {
                        $options[$key](...$args);
                    }
                } catch (Throwable $e) {
                    echo $e;
                }
            };
        }
        return $options;
    }

    /**
     * 格式化信息(国内一些模型用到)
     * @param array $messages
     * @return array
     */
    public static function formatMessages(array $messages): array
    {
        if ($messages[0]["role"] === "system") {
            $messages[0]["role"] = "user";
            // 如果第二条也是user则插入一条assistant的ok消息
            if (isset($messages[1]) && $messages[1]["role"] === "user") {
                array_splice($messages, 1, 0, [[
                    "role" => "assistant",
                    "content" => "ok"
                ]]);
            }
        }

        // 国内接口要求第一条的role必须是user，如果不是则删除掉
        while (count($messages) > 0 && $messages[0]["role"] !== "user") {
            array_shift($messages);
        }

        // 空消息设置为空格避免报错
        foreach ($messages as $index => $message) {
            $messages[$index]["content"] = $message["content"] ?: " ";
        }

        // 强制格式化消息为user assistant交错的信息
        $mergedMessages = [];
        $currentRole = null;
        for ($i = 0; $i < count($messages); $i++) {
            $role = $messages[$i]["role"];
            $content = $messages[$i]["content"];
            if ($role !== $currentRole) {
                $mergedMessages[] = array("role" => $role, "content" => $content);
                $currentRole = $role;
            } else {
                $mergedMessages[count($mergedMessages) - 1]["content"] .= " " . $content;
            }
        }
        return $mergedMessages;
    }

}